import datetime
import json
import os

from flask_restful import Resource, reqparse
from flask import jsonify, request

from app.feijiang.handler import pps_ai
from app.utils.decorator import add_api_resource
from app.utils.error_code import ErrorCode
from app.utils.tools import generate_random_string


@add_api_resource('/v1/api/ppfj/img/rec')
class PPFeijiangRec(Resource):
    """查询书刊杂志
    """

    def post(self):
        data = request.files.get('file')
        print(data.filename)
        if not data:
            return jsonify(ErrorCode.file_is_not_upload)
        file_name = '%s_%s.png' % (datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
                               generate_random_string())
        file_path = file_name
        with open(file_path, 'wb') as f:
            f.write(data.read())
        f.close()
        return self.hander(file_path)

    def hander(self, file_path):
        result = pps_ai.rec_img(file_path)
        return_data = {'error': 0, 'error_msg': 'success', 'data':str(result)}
        os.remove(file_path)
        return jsonify(return_data)


@add_api_resource('/v1/api/test')
class ApiTest(Resource):

    def get(self):
        return jsonify(ErrorCode.success_status)